package com.tqz.juc.atomic;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * <p>演示CAS下产生的ABA问题.
 * 可使用 {@link AtomicStampedReference} 增加版本号来解决该问题.
 *
 * @author tianqingzhao
 * @since 2022/2/6 18:37
 */
public class AtomicABATest {
    
    static AtomicInteger value = new AtomicInteger(1);
    
    public static void main(String[] args) throws InterruptedException {
        Thread main = new Thread(() -> {
            int before = value.get();
            System.out.println("主线程修改之前：" + before);
    
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            boolean success = value.compareAndSet(before, 2);
            if (success) {
                System.out.println("主线程CAS修改成功，修改之后的值：" + value.get());
            } else {
                System.out.println("主线程修改失败");
            }
        }, "main");
        
        Thread other = new Thread(() -> {
            System.out.println("子线程第一次操作修改之后的值："  + value.incrementAndGet());
            value.decrementAndGet();
            System.out.println("子线程第二次操作修改之后的值：" + value.get());
        }, "other");
        
        main.start();
        Thread.sleep(500);
        other.start();
    }
    
}
